<template>
  <div
    class="chat-pc layout-bg chat-pc-new"
    :class="classObj"
    v-loading="loading"
    :style="{
      '--el-color-primary': applicationDetail?.custom_theme?.theme_color,
      '--el-color-primary-light-9': hexToRgba(applicationDetail?.custom_theme?.theme_color, 0.1)
    }"
  >
    <div class="flex-row">
      <div class="left" v-if="!hasCustomAgent">
        <transition>
          <div class="left-title" v-if="isCollapse">
            <span>对话历史</span>
            <img src="@/assets/agent/chat/shouqi.svg" alt="" @click="isCollapse = !isCollapse">
          </div>
          <img v-else class="top-icon" src="@/assets/agent/chat/shouqi.svg" alt="" @click="isCollapse = !isCollapse">
        </transition>
        <div class="flex-1">
          <div class="left-content">
            <div class="text-center" v-if="chatLogData.length === 0 && isCollapse">
              <el-text type="info">{{ $t('chat.noHistory') }}</el-text>
            </div>
            <div v-for="(v, i) in chatLogData" :class="{'left-content-item': true, 'active': currentActive === (v as any).id }" :key="i" @click="clickListHandle(v)" @mouseenter.stop="showMoreId = (v as any).id">
              <img class="left-content-item-left" :src="applicationDetail?.avatar" alt="img">
              <transition>
                <div class="left-content-item-right" v-if="isCollapse">
                  <div class="left-content-item-right-title">
                    {{ v.abstract }}
                  </div>
                  <div class="left-content-item-right-time">
                    {{ dayjs().format('HH:mm') }}
                  </div>
                </div >
              </transition>
              <transition @click.stop>
                <el-dropdown v-if="isCollapse && v.id !== 'new'" trigger="hover">
                  <div class="left-content-item-more">
                    <img src="@/assets/agent/chat/more.svg" alt="" >
                  </div>
                  <template #dropdown>
                    <el-dropdown-menu :teleported="false">
                      <el-dropdown-item @click="deleteLog(v)">删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </transition>
            </div>
          </div>
        </div>
        <div class="left-add" :style="{ border: isCollapse ? '1px solid rgba(48,103,239,0.6)' : 'none'}">
          <el-button class="button" v-if="isCollapse" :icon="Plus" round style="width: 100%" @click="agentVisible = true">新建对话</el-button>
          <el-icon v-else :size="32" color="#3067EF" style="cursor: pointer">
            <CirclePlus @click="agentVisible = true" />
          </el-icon>
        </div>
      </div>
      <div class="right">
        <div class="right-height chat-width">
          <CustomizationAiChat
              v-if="hasCustomAgent"
              v-model:applicationDetails="applicationDetail"
              :appId="applicationDetail?.id"
              :chatId="currentChatId"
              :type="hasCustomAgent"
          />
          <AiChatNew
            v-else
            ref="AiChatRef"
            v-model:applicationDetails="applicationDetail"
            :available="applicationAvailable"
            type="ai-chat"
            :appId="applicationDetail?.id"
            :record="currentRecordList"
            :chatId="currentChatId"
            @refresh="refresh"
            @scroll="handleScroll"
          >
          </AiChatNew>
        </div>
      </div>
    </div>
    <AgentList
      @tab-click="handleTabClick"
      @tab-close="agentVisible = false"
      :dialogVisible="agentVisible"
      :title="'选择智能体以新建对话'" />
  </div>
</template>

<script setup lang="ts">
import router from '@/router'
import dayjs from 'dayjs'
import { ref, onMounted, nextTick, computed } from 'vue'
import useStore from '@/stores'
import useResize from '@/layout/hooks/useResize'
import { hexToRgba } from '@/utils/theme'
import { t } from '@/locales'
import { CirclePlus, Plus } from '@element-plus/icons-vue'
import AgentList from '@/views/agent/components/AgentList.vue'
import { useRoute } from 'vue-router'
// 定制AiChat
import CustomizationAiChat from '../components/index.vue'
import defImg from '@/assets/agent/def_agent.svg'
useResize()

const hasCustomAgent = computed(() => applicationDetail.value.renderingType !== '')


const agentVisible = ref(false);



const handleTabClick = (item: any) => {
  if (applicationDetail.value.id === item.maxId) {
    newChat()
    agentVisible.value = false;
    return
  }
  localStorage.setItem('avatar', item.imgUrl || '')
  localStorage.setItem('renderingType', item.renderingType || '')
  if (item.ty_type === 1) {
    router.push('/agent/chat/' + item.max_ty_type_url)
    return
  }
  const shareUrl = '/agent/chat/' + item?.access_token
  router.push(shareUrl)
  // agentVisible.value = false;
  // localStorage.setItem('avatar', item.imgUrl || '')
  // applicationDetail.value = item;
  // init();
}
const currentActive = ref('');
const showMoreId = ref('');

const { user, log, common, application } = useStore()


const isCollapse = ref(true)


const classObj = computed(() => {
  return {
    mobile: common.isMobile(),
    hideLeft: !isCollapse.value,
  }
})

const newObj = {
  id: 'new',
  abstract: t('chat.createChat')
}
const props = defineProps<{
  application_profile: any
  applicationAvailable: boolean
}>()
const emit = defineEmits(['update:application_profile']);
const AiChatRef = ref()
const loading = ref(false)
const left_loading = ref(false)

const applicationDetail = computed({
  get: () => {
    return {
      ...props.application_profile,
      avatar: localStorage.getItem('avatar') || defImg,
      renderingType: localStorage.getItem('renderingType') || ''
    }
  },
  set: (v) => {
    emit('update:application_profile', v);
  }
})

const chatLogData = ref<any[]>([])

const paginationConfig = ref({
  current_page: 1,
  page_size: 20,
  total: 0
})

const currentRecordList = ref<any>([])
const currentChatId = ref('new') // 当前历史记录Id 默认为'new'
const currentChatName = ref(t('chat.createChat'))

function deleteLog(row: any) {
  log.asyncDelChatClientLog(applicationDetail.value.id, row.id, left_loading).then(() => {
    if (currentChatId.value === row.id) {
      currentChatId.value = 'new'
      currentChatName.value = t('chat.createChat')
      paginationConfig.value.current_page = 1
      paginationConfig.value.total = 0
      currentRecordList.value = []
    }
    getChatLog(applicationDetail.value.id)
  })
}

function handleScroll(event: any) {
  if (
    currentChatId.value !== 'new' &&
    event.scrollTop === 0 &&
    paginationConfig.value.total > currentRecordList.value.length
  ) {
    const history_height = event.dialogScrollbar.offsetHeight
    paginationConfig.value.current_page += 1
    getChatRecord().then(() => {
      event.scrollDiv.setScrollTop(event.dialogScrollbar.offsetHeight - history_height)
    })
  }
}

function newChat() {
  if (!chatLogData.value.some((v) => v.id === 'new')) {
    paginationConfig.value.current_page = 1
    paginationConfig.value.total = 0
    currentRecordList.value = []
    chatLogData.value.unshift(newObj)
  } else {
    paginationConfig.value.current_page = 1
    paginationConfig.value.total = 0
    currentRecordList.value = []
  }
  currentChatId.value = 'new'
  currentChatName.value = t('chat.createChat')
  if (common.isMobile()) {
    isCollapse.value = false
  }
}
function getChatLog(id: string, refresh?: boolean) {
  const page = {
    current_page: 1,
    page_size: 20
  }

  log.asyncGetChatLogClient(id, page, left_loading).then((res: any) => {
    chatLogData.value = res.data.records
    if (refresh) {
      currentChatName.value = chatLogData.value?.[0]?.abstract
    } else {
      newChat()
      paginationConfig.value.current_page = 1
      paginationConfig.value.total = 0
      currentRecordList.value = []
      currentChatId.value = chatLogData.value?.[0]?.id || 'new'
      currentChatName.value = chatLogData.value?.[0]?.abstract || t('chat.createChat')
      if (currentChatId.value !== 'new') {
        getChatRecord()
      }
    }
  })
}

function getChatRecord() {
  return log
    .asyncChatRecordLog(
      applicationDetail.value.id,
      currentChatId.value,
      paginationConfig.value,
      loading,
      false
    )
    .then((res: any) => {
      paginationConfig.value.total = res.data.total
      const list = res.data.records
      list.map((v: any) => {
        v['write_ed'] = true
        v['record_id'] = v.id
      })
      currentRecordList.value = [...list, ...currentRecordList.value].sort((a, b) =>
        a.create_time.localeCompare(b.create_time)
      )
      if (paginationConfig.value.current_page === 1) {
        nextTick(() => {
          // 将滚动条滚动到最下面
          AiChatRef.value.setScrollBottom()
        })
      }
    })
}

const clickListHandle = (item: any) => {
  if (item.id !== currentChatId.value) {
    paginationConfig.value.current_page = 1
    paginationConfig.value.total = 0
    currentRecordList.value = []
    currentChatId.value = item.id
    currentChatName.value = item.abstract
    if (currentChatId.value !== 'new') {
      getChatRecord()

      // 切换对话后，取消暂停的浏览器播放
      if (window.speechSynthesis.paused && window.speechSynthesis.speaking) {
        window.speechSynthesis.resume()
        nextTick(() => {
          window.speechSynthesis.cancel()
        })
      }
    }
  }
  if (common.isMobile()) {
    isCollapse.value = false
  }
}

function refresh(id: string) {
  getChatLog(applicationDetail.value.id, true)
  currentChatId.value = id
}

/**
 *初始化历史对话记录
 */
const init = () => {
  if (
    (applicationDetail.value.show_history || !user.isEnterprise()) &&
    props.applicationAvailable
  ) {
    getChatLog(applicationDetail.value.id)
  }
}
onMounted(() => {
  init()
})
</script>
<style lang="scss">
@import "./index.scss";
</style>
